#ifndef _PROCESS_POOL_HPP_
#define _PROCESS_POOL_HPP_

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <vector>

// 单个信道的描述
class Channel
{
public:
    Channel(int wfd, int id) : _wfd(wfd), _id(id)
    {
        _name = "channel-"  + std::to_string(id) + "-" + std::to_string(_wfd);
    }
    ~Channel() {}
    std::string GetName() { return _name; }
private:
    int _wfd;
    pid_t _id;
    std::string _name;
};

// 对多个信道的描述
class ChannelManager
{
public:
    ChannelManager() {}
    void ChannelInsert(int wfd, pid_t id)
    {
        channels.emplace_back(wfd, id); // 先调用构造函数构造对象之后进行插入channels
    }
    void PrintChannels()
    {
        for(auto& ch : channels)
        {
            std::cout << "channel.name:" << ch.GetName() << std::endl;
        }
    }
    ~ChannelManager() {}

private:
    std::vector<Channel> channels;
};

int gdefaultnum = 5;
// 进程池
class ProcessPool
{
public:
    ProcessPool(int processnum) : _processnum(processnum)
    {
    }
    // 子进程的工作
    void Work(int rfd, pid_t id)
    {
        // while (true)
        // {
        //     int code = 0;
        //     ssize_t n = read(rfd, &code, sizeof(code));
        // }
        std::cout << "我是一个子进程, 我的rfd : " << rfd << std::endl; 
    }
    bool Create()
    {
        for (int i = 0; i < _processnum; i++)
        {
            // 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            pid_t id = fork();
            if (id < 0)
                return false;
            else if (id == 0)
            {
                close(pipefd[1]);
                Work(pipefd[0], id);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                close(pipefd[0]);
                // 走到此处已经创建了一个管道和子进程，就要开始添加信道
                _cm.ChannelInsert(pipefd[1], id);
                close(pipefd[1]);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.PrintChannels();
    }
    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _processnum;
};

#endif